<template>
  <div class="w100 baselight theme-dark">
    <div class="flex alcenter mt5 vh80" style="min-height: 710px">
      <div class="flex1 flex column h100 mr5">
        <div class="flex h100">
          <div class="flex2 flex column mr5">
            <div class="flex2">
              <div class="bgheader bdbheader flex alcenter plr10 ht40">
                <div class="_property">
                  <a-popover class="baselight2 ft16 bold mr20 pointer">
                    <template slot="content">
                      <div class="popover-box">
                        <div class="flex alcenter mt10 mb10">
                          <span class="flex1 pl10">{{ $t('Currency') }}</span>
                          <span class="flex1 tr">{{ $t('latest price') }}</span>
                          <span class="flex1 tr pr10">{{ $t('Increase') }}</span>
                        </div>
                        <div class="overyscroll">
                          <div class="popover-body">
                            <div
                              v-for="(item, index) in stockList"
                              :key="index"
                              :class="[
                                'flex alcenter ptb5 markethover pointer',
                                stockCode === item.code ? 'bgshadow' : ''
                              ]"
                              @click="stockToggleHandler(item)"
                            >
                              <div class="flex1 pl10 baselight2">{{ item.name }}</div>
                              <div class="flex1 tr baselight2">{{ item.price }}</div>
                              <div :class="['flex1 tr pr10', item.priceflu > 0 ? 'green' : 'red']">
                                <!-- <span>+</span> -->
                                {{ item.priceflu }}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </template>
                    <div class="flex alcenter">
                      <span style="vertical-align: inherit">{{ stockInfo.name }}</span>
                      <a-icon type="caret-down" />
                    </div>
                  </a-popover>
                </div>
                <div>
                  <div class="ft16 green">{{ stockInfo.price }}</div>
                </div>
                <div class="flex1 ft12 flex ml30">
                  <div class="mr30">
                    <div class="flex1">{{ $t('Increase') }}</div>
                    <div class="flex1 green">{{ stockInfo.priceflu }}%</div>
                  </div>
                  <div class="mr30">
                    <div class="flex1">{{ $t('Highest price') }}</div>
                    <div class="flex1 baselight2">{{ stockInfo.highPrice }}</div>
                  </div>
                  <div class="mr30">
                    <div class="flex1">{{ $t('Lowest price') }}</div>
                    <div class="flex1 baselight2">{{ stockInfo.lowPrice }}</div>
                  </div>
                  <!-- <div class="mr30">
                    <div class="flex1">24H量</div>
                    <div class="flex1 baselight2">NaN</div>
                  </div> -->
                </div>
              </div>
              <div class="chart">
                <comm-chart ref="CommChart" style="width: 100%; height: 80vh"></comm-chart>
              </div>
            </div>
          </div>
          <div class="flex column overy" style="width: 300px; height: 100%">
            <div class="flex">
              <div class="bdbheader flex alcenter bold bgheader flex1 pt7 pl5">
                <div
                  :class="[
                    'pb10 mr20 pointer ft14 bd2px',
                    handicapOrTrade === 'handicap' ? 'active2px' : ''
                  ]"
                  @click="() => (handicapOrTrade = 'handicap')"
                >
                  {{ $t('handicap') }}
                </div>
                <div
                  :class="[
                    'pb10 mr20 pointer ft14 bd2px',
                    handicapOrTrade === 'transaction' ? 'active2px' : ''
                  ]"
                  @click="() => (handicapOrTrade = 'transaction')"
                >
                  {{ $t('Full station transaction') }}
                </div>
              </div>
            </div>
            <div class="flex1 flex">
              <div v-if="handicapOrTrade == 'handicap'" class="flex column w100 flex1 bgpart">
                <div class="ptb10 flex1 flex column w100">
                  <div class="flex alcenter plr10">
                    <span class="flex1"> {{ $t('Direction') }} </span>
                    <span class="flex1 tc">{{ $t('Price') }}</span>
                    <span class="flex1 tr"> {{ $t('Number') }} </span>
                  </div>
                  <div class="mtb10 flex1 flex column jsend asks">
                    <div
                      v-for="(item, index) in inlistSocket[stockCode]"
                      :key="index"
                      class="ptb5 flex alcenter pointer h100 plr10"
                      :style="{ backgroundSize: `${(item.num / inlistSum) * 200}% 100%` }"
                      style="
                        transition: 0.8s;
                        background-size: 5% 100%;
                        background-position: 100%;
                        background-repeat: no-repeat;
                        background-image: linear-gradient(
                          rgba(250, 82, 82, 0.1),
                          rgba(250, 82, 82, 0.1)
                        );
                      "
                    >
                      <template v-if="index < 10">
                        <span class="flex1 red"> {{ $t('Sell') }}{{ index + 1 }} </span>
                        <span class="flex1 tc baselight2"> {{ item.amount }} </span>
                        <span class="flex1 tr baselight2"> {{ item.num }} </span>
                      </template>
                    </div>
                  </div>
                  <div class="ptb15 bdtheader bdbheader plr10">
                    <span class="red bold ft20"> {{ parseFloat(stockInfo.price || 0) }}</span>
                  </div>
                  <div class="bgpart mt10 flex1 flex column bids">
                    <div
                      v-for="(item, index) in outlistSocket[stockCode]"
                      :key="index"
                      class="ptb5 flex alcenter pointer h100 plr10"
                      :style="{ backgroundSize: `${(item.num / outlistSum) * 200}% 100%` }"
                      style="
                        transition: 0.8s;
                        background-size: 5% 100%;
                        background-position: 100%;
                        background-repeat: no-repeat;
                        background-image: linear-gradient(
                          rgba(18, 184, 134, 0.1),
                          rgba(18, 184, 134, 0.1)
                        );
                      "
                    >
                      <template v-if="index < 10">
                        <span class="flex1 green"> {{ $t('Buy') }}{{ 10 - index }} </span>
                        <span class="flex1 tc baselight2"> {{ item.amount }} </span>
                        <span class="flex1 tr baselight2"> {{ item.num }} </span>
                      </template>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="flex1 bgpart overy flex">
                <div class="ptb10 flex1 flex column w100">
                  <div class="flex alcenter plr10">
                    <span class="flex1">
                      <font style="vertical-align: inherit">
                        <font style="vertical-align: inherit">{{ $t('Time') }}</font>
                      </font>
                    </span>
                    <span class="flex1 tc">
                      <font style="vertical-align: inherit">
                        <font style="vertical-align: inherit">{{ $t('Price') }}</font>
                      </font>
                    </span>
                    <span class="flex1 tr">
                      <font style="vertical-align: inherit">
                        <font style="vertical-align: inherit">{{ $t('Number') }}</font>
                      </font>
                    </span>
                  </div>
                  <div class="flex1 mt10">
                    <div class="overyscroll plr10" style="height: 660px">
                      <div class="ptb5 flex alcenter">
                        <span class="flex1">18:13:46</span>
                        <span class="flex1 tc red">3048.360000000</span>
                        <span class="flex1 tr baselight2">0.000100000</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="bgpart" style="width: 290px; height: 100%">
            <div class="bgheader bdbheader flex alcenter plr10 baselight2 mb10">
              <div
                :class="['ptb5 mr10 bold ft14 pointer', ruleForm.orderType == 1 ? 'active2px' : '']"
                style="margin-bottom: 7px"
                @click="tradeHandler(1)"
              >
                {{ $t('Limit Price Trading') }}
              </div>
              <div
                :class="['ptb5 mr10 bold ft14 pointer', ruleForm.orderType == 2 ? 'active2px' : '']"
                style="margin-bottom: 7px"
                @click="tradeHandler(2)"
              >
                {{ $t('market price transaction') }}
              </div>
            </div>
            <div class="flex mlr10 pointer" style="border-radius: 2px; overflow: hidden">
              <div
                class="flex1 posRelt bggreen"
                style="
                  height: 34px;
                  text-align: center;
                  line-height: 34px;
                  color: rgb(255, 255, 255);
                  font-size: 16px;
                "
                @click="buyCoin()"
              >
                <span style="vertical-align: inherit">{{ $t('Buy') }}</span>
                <div
                  class="abstort top0 rt0 btm0"
                  style="
                    border-top: 16px solid rgb(11, 14, 17);
                    border-left: 16px solid transparent;
                    border-bottom: 18px solid rgb(11, 14, 17);
                  "
                ></div>
              </div>
              <div
                class="flex1 posRelt bgred"
                style="
                  height: 34px;
                  text-align: center;
                  line-height: 34px;
                  color: rgb(255, 255, 255);
                  font-size: 16px;
                "
                @click="sellCoin()"
              >
                <span style="vertical-align: inherit"> {{ $t('Sell') }} </span>
                <div
                  class="abstort top0 lf0 btm0"
                  style="
                    border-top: 16px solid rgb(11, 14, 17);
                    border-right: 16px solid transparent;
                    border-bottom: 18px solid rgb(11, 14, 17);
                  "
                ></div>
              </div>
            </div>
            <div class="flex ft12">
              <div class="flex1 plr10 mt10 bdr38">
                <div class="flex alcenter">
                  <span style="vertical-align: inherit">
                    {{ $t('available') }}
                    {{ ruleForm.type === 'buy' ? accountAmount : coinAmount }}
                    {{ ruleForm.type === 'buy' ? 'USDT' : stockInfo.name }}
                  </span>
                </div>
                <div class="mb10 posRelt">
                  <a-form-model>
                    <a-form-model-item :label="BuyOrSell + ' ' + $t('Price')" class="m0">
                      <a-input
                        ref="userNameInput"
                        v-model="ruleForm.price"
                        :disabled="ruleForm.orderType == '2'"
                        :placeholder="
                          ruleForm.orderType == '2' ? $t('Buy at the best price in the market') : ''
                        "
                        @change="handlePrice"
                      >
                        <span slot="suffix"> USDT </span>
                      </a-input>
                    </a-form-model-item>
                    <a-form-model-item :label="BuyOrSell + ' ' + $t('Total')" class="mb10">
                      <a-input ref="userNameInput" v-model="ruleForm.num">
                        <span slot="suffix"> {{ stockInfo.name }} </span>
                      </a-input>
                    </a-form-model-item>
                    <!-- <a-form-model-item> -->
                    <!-- <a-slider :step="10" :default-value="37" /> -->
                    <!-- <Slider /> -->
                    <a-slider
                      :marks="marks"
                      :step="25"
                      style="margin-bottom: 10px"
                      @change="changeSlider"
                      v-model="sliderValue"
                    />
                    <!-- </a-form-model-item> -->
                    <div class="flex alcenter mb10">
                      {{ $t('transaction amount') }} {{ transactionAmount }} USDT
                    </div>
                    <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
                      <a-button
                        :loading="submitLoading"
                        :style="{
                          color: '#0B0E11',
                          backgroundColor: ruleForm.type === 'buy' ? '#00AB86' : '#ff6064'
                        }"
                        block
                        size="large"
                        @click="onSubmit"
                      >
                        {{ ruleForm.type === 'buy' ? $t('Buy') : $t('Sell') }}
                      </a-button>
                    </a-form-model-item>
                  </a-form-model>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="mt5 bgpart">
      <a-tabs v-model="filter.type" @click="loadData">
        <a-tab-pane key="1" :tab="$t('Current delegate')"></a-tab-pane>
        <a-tab-pane key="2" :tab="$t('All delegates')"></a-tab-pane>
        <div slot="tabBarExtraContent" class="flex alcenter pr15">
          <div
            :class="[
              'plr5 tc ft12 baselight2 plr10  mr30 pointer',
              filter.orderType == 'buy' ? 'green bdbgreen' : ''
            ]"
            @click="() => (filter.orderType = 'buy')"
          >
            {{ $t('Buy') }}
          </div>
          <div
            :class="[
              'plr5 tc ft12 baselight2 plr10  pointer',
              filter.orderType == 'sell' ? 'red bdbred' : ''
            ]"
            @click="() => (filter.orderType = 'sell')"
          >
            {{ $t('Sell') }}
          </div>
        </div>
      </a-tabs>
      <a-table
        :columns="
          filter.type == 1
            ? [
                ...columns,
                {
                  dataIndex: 'Operation',
                  key: 'Operation',
                  title: $t('Operation'),
                  scopedSlots: { customRender: 'action' }
                }
              ]
            : columns
        "
        :data-source="dataSource"
        :pagination="false"
        style="color: #fff"
      >
        <template slot="action" slot-scope="text, record">
          <a-button type="primary" @click="cancelOrderHandler(record)">{{
            $t('Cancel Order')
          }}</a-button>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script>
import websocket from '@/utils/websocket'
import commChart from '@/components/commChart.vue'
// import Slider from '@/components/slider'
import { mapState, mapActions } from 'vuex'
import { fetchAccount } from '@/api/asset'
import _ from 'lodash'
import {
  getChargeList,
  fetchChargeCance,
  getStockInfo,
  getStockCodeInfo,
  fetchChargeTrade
} from '@/api/stock'

export default {
  components: {
    commChart
  },
  data() {
    return {
      filter: {
        name: '', // 币种
        orderType: 'buy',
        type: '1'
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      ruleForm: {
        orderType: '1',
        type: 'buy',
        price: ''
      },
      handicapOrTrade: 'handicap',
      dataSource: [],
      columns: [
        {
          dataIndex: 'createTime',
          key: 'createTime',
          title: this.$t('Time')
        },
        {
          dataIndex: 'amount',
          key: 'amount',
          title: this.$t('trading amount')
        },
        {
          dataIndex: 'type',
          key: 'type',
          title: this.$t('direction')
        },
        {
          dataIndex: 'price',
          key: 'price',
          title: this.$t('Price')
        },
        {
          dataIndex: 'name',
          key: 'name',
          title: this.$t('coin')
        },
        {
          dataIndex: 'num',
          key: 'num',
          title: this.$t('volume')
        }
      ],
      stockList: [],
      stockCode: '',
      stockInfo: {},
      inlistSocket: {},
      outlistSocket: {},
      submitLoading: false,
      accountAmount: 0,
      coinAmount: 0,
      inlistSum: 0,
      outlistSum: 0,
      marks: {
        25: '',
        50: '',
        75: '',
        100: ''
      },
      currentRangeValue: 0,
      sliderValue: 0
    }
  },
  computed: {
    BuyOrSell() {
      return this.ruleForm.type == 'buy' ? this.$t('Buy') : this.$t('Sell')
    },
    transactionAmount() {
      const { price, num } = this.ruleForm
      return price && num ? price * num : 0
    },
    ...mapState({
      user: (state) => state.info
    }),
    debouncedPriceHandler() {
      return _.debounce(() => {
        this.changeSlider(this.currentRangeValue);
      }, 200);
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    ...mapActions(['GetUserInfo']),
    handlePrice(){
      this.debouncedPriceHandler()
    },
    /**
     * 检查值是否为有限数（非 Infinity、-Infinity 和 NaN）
     */
    isFiniteNumber(value) {
      return typeof value === 'number' && isFinite(value)
    },
    changeSlider(val) {
      this.currentRangeValue = val
      const { ruleForm, accountAmount, coinAmount, stockInfo } = this
      const vm = this
      const range = { 25: 4, 50: 3, 75: 2, 100: 1 }
      // '1/4', '1/3', '1/2', 'Full'
      // eslint-disable-next-line no-debugger
      if (ruleForm.type === 'buy') {
        let balance = accountAmount
        let total = 0
        if (ruleForm.orderType == 2) {
          total = (+balance / +stockInfo.price / range[val])
        } else {
          total = +balance / range[val] / +ruleForm.price
        }
        vm.$set(vm.ruleForm, 'num', vm.isFiniteNumber(total) ? (total || 0).toFixed(4) : 0)
      } else {
        let num = coinAmount || 0
        // vm.ruleForm.num = Math.trunc(num / range[val]) || 0
        vm.$set(vm.ruleForm, 'num', (num / range[val]).toFixed(4) || 0)
      }
    },
    onSubmit() {
      this.submitLoading = true
      fetchChargeTrade({ ...this.ruleForm, name: this.stockInfo.name })
        .then(() => {
          this.submitLoading = false
          this.$Success()
          this.loadData()
          this.getAccount()
          this.GetUserInfo()
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    tradeHandler(type) {
      if(this.ruleForm.orderType != type){
        this.ruleForm.orderType = type
        this.sliderValue = 0
        this.currentRangeValue = 0
        this.ruleForm.price = ''
        this.ruleForm.num = ''
      }

    },
    cancelOrderHandler(record) {
      console.log(record)
      fetchChargeCance(record.id).then(() => {
        this.$Success()
        this.loadData()
      })
    },
    init() {
      getStockInfo().then((resp) => {
        this.stockList = resp.data
        if (this.$route.query.code) {
          this.stockCode = this.$route.query.code
          this.stockInfo.name = this.$route.query.name
          // this.getDetail(this.$route.query.code)
        } else {
          this.stockCode = this.stockList[0].code
          this.stockInfo = this.stockList[0]
        }
        this.getDetail(this.stockCode)
      })
      this.loadData()
      this.getAccount()
    },
    loadData() {
      getChargeList(this.filter).then((resp) => {
        this.dataSource = resp.data
      })
    },
    getAccount() {
      fetchAccount({ type: 'trade', name: 'USDT' }).then((resp) => {
        this.accountAmount = resp.data
      })
    },
    buyCoin() {
      this.ruleForm.type = 'buy'
      this.ruleForm.price = ''
      this.ruleForm.num = ''
      this.sliderValue = 0
      this.currentRangeValue = 0
      fetchAccount({ type: 'trade', name: 'USDT' }).then((resp) => {
        this.accountAmount = resp.data
      })
    },
    sellCoin() {
      this.ruleForm.type = 'sell'
      this.ruleForm.price = ''
      this.ruleForm.num = ''
      this.sliderValue = 0
      this.currentRangeValue = 0
      fetchAccount({ type: 'trade', name: this.stockInfo.name }).then((resp) => {
        this.coinAmount = resp.data
      })
    },
    getDetail(code) {
      const vm = this
      getStockCodeInfo(code).then((resp) => {
        const response = resp.data
        vm.fetchHandicap(response)
        new websocket(function (data) {
          if (data.code == response.code) {
            response.price = data.price
            response.priceflu = data.priceflu
            response.highPrice = data.highPrice
            response.lowPrice = data.lowPrice
            vm.fetchHandicap(response)
          }
        })
        this.stockInfo = response
        this.changeType()
      })
    },
    fetchHandicap(response) {
      if ((response.price + '').indexOf('.') === -1) {
        response.price = response.price + '.01'
      }
      const inlistSocket = this.getLowerNumbers(parseFloat(response.price + '')).reverse()
      const outlistSocket = this.getUpperNumbers(parseFloat(response.price + ''))
      // const nearbyNums = this.generateNearbyAmounts(Math.round(Math.random()));
      // const originalIndex = nearbyAmounts.indexOf(Number(response.price));
      const nearbyData1 = []
      for (let i = 0; i < inlistSocket.length; i++) {
        let element1 = this.inlistSocket[i]
        if (!element1) {
          element1 = {}
        }
        // Number(inlistSocket[i]) !== Number(element1.amount) ? element1.num : Math.random().toFixed(4)
        nearbyData1.push({
          name: i,
          amount: inlistSocket[i],
          num: Math.random().toFixed(4)
        })
      }
      const nearbyData2 = []
      for (let i = 0; i < outlistSocket.length; i++) {
        let element = this.outlistSocket[i]
        if (!element) {
          element = {}
        }
        nearbyData2.push({
          name: i,
          amount: outlistSocket[i],
          num: Math.random().toFixed(4)
        })
      }
      this.inlistSocket[response.code] = nearbyData1
      //统计inlistSocket 中num
      this.inlistSum = nearbyData1.reduce((sum, item) => sum + +item.num, 0)
      this.outlistSocket[response.code] = nearbyData2
      this.outlistSum = nearbyData2.reduce((sum, item) => sum + +item.num, 0)
    },
    getLowerNumbers(num) {
      // 检查输入是否为浮点数
      if (typeof num !== 'number' || num % 1 === 0) {
        return '请输入一个浮点数'
      }

      // 获取小数部分的精度
      let precision = Math.pow(10, num.toString().split('.')[1].length)

      // 计算下10个数字
      let result = []
      for (let i = 1; i <= 10; i++) {
        result.push((num - i / precision).toFixed(num.toString().split('.')[1].length))
      }

      return result
    },
    getUpperNumbers(num) {
      // 检查输入是否为浮点数
      if (typeof num !== 'number' || num % 1 === 0) {
        return '请输入一个浮点数'
      }

      // 获取小数部分的精度
      let precision = Math.pow(10, num.toString().split('.')[1].length)

      // 计算上10个数字
      let result = []
      for (let i = 1; i <= 10; i++) {
        result.push((num + i / precision).toFixed(num.toString().split('.')[1].length))
      }

      return result
    },
    changeType() {
      this.$refs.CommChart.ChangeSymbol(this.stockInfo.code, this.stockInfo.name)
    },
    stockToggleHandler(item) {
      if (this.stockCode != item.code) {
        this.stockCode = item.code
        this.getDetail(item.code)
      }
    },
    generateNearbyAmounts(amount) {
      // 将金额转换为整数形式，方便处理最后两位
      const amountInt = Math.round(amount * 100)

      // 获取最后两位数字
      const lastTwoDigits = amountInt % 100

      // 计算上下各 10 个数字的范围
      const lowerBound = Math.max(0, lastTwoDigits - 10) // 防止小于 0
      const upperBound = Math.min(99, lastTwoDigits + 10) // 防止大于 99

      // 生成附近的数字数组
      const nearbyDigits = []
      for (let i = lowerBound; i <= upperBound; i++) {
        nearbyDigits.push(i)
      }

      // 将这些数字转换回对应的金额形式
      const nearbyAmounts = nearbyDigits.map((digit) => {
        // 去掉原始金额的最后两位，加上新的数字
        const newAmountInt = Math.floor(amountInt / 100) * 100 + digit
        return newAmountInt / 100 // 转换回浮点数形式
      })

      return nearbyAmounts
    }
  }
}
</script>

<style lang="scss" scoped>
.m0 {
  margin: 0;
}

.posRelt {
  :deep(.ant-form-item-label),
  :deep(.ant-form-item-control) {
    line-height: 30px;
  }

  :deep(.ant-input) {
    height: 30px;
  }
}

.bdbgreen {
  border-bottom: 2px solid #52db72;
}

.bdbred {
  border-bottom: 2px solid #ff6064;
}

:deep(.ant-tabs-extra-content) {
  line-height: 30px;
}
</style>
